# app/models/file.py
from app import db
from datetime import datetime

class File(db.Model):
    __tablename__ = 'files'

    file_id = db.Column(db.String(36), primary_key=True)
    uploader_id = db.Column(db.String(36), db.ForeignKey('users.user_id'), nullable=False)
    channel_id = db.Column(db.String(36), db.ForeignKey('channels.channel_id'))
    direct_chat_id = db.Column(db.String(36), db.ForeignKey('direct_chats.chat_id'))
    original_name = db.Column(db.String(255), nullable=False)  # 合并原始名和存储名
    stored_name = db.Column(db.String(255), nullable=False)
    mime_type = db.Column(db.String(100), nullable=False)
    size = db.Column(db.BigInteger, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    file_url = db.Column(db.String(255))
    uploader = db.relationship('User', back_populates='files_uploaded')

    # 确保消息必须属于频道或私聊中的一种
    __table_args__ = (
        db.CheckConstraint(
            '(channel_id IS NOT NULL AND direct_chat_id IS NULL) OR '
            '(channel_id IS NULL AND direct_chat_id IS NOT NULL)',
            name='chk_message_source'
        ),
    )

    def __repr__(self):
        return f'<File {self.filename}>'


# 添加分片上传模型
class FileUploadTask(db.Model):
    __tablename__ = 'file_upload_tasks'

    task_id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    file_id = db.Column(db.String(36), db.ForeignKey('files.file_id'))
    uploader_id = db.Column(db.String(36), db.ForeignKey('users.user_id'))
    original_name = db.Column(db.String(255), nullable=False)
    mime_type = db.Column(db.String(100), nullable=False)
    total_size = db.Column(db.BigInteger, nullable=False)
    total_chunks = db.Column(db.Integer, nullable=False)
    uploaded_chunks = db.Column(db.Integer, default=0)
    status = db.Column(db.String(20), default='uploading')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    # 添加关系
    file = db.relationship('File', backref='upload_task')
    uploader = db.relationship('User', backref='upload_tasks')


# 添加分片模型
class FileChunk(db.Model):
    __tablename__ = 'file_chunks'

    id = db.Column(db.Integer, primary_key=True)
    task_id = db.Column(db.String(36), db.ForeignKey('file_upload_tasks.task_id'), nullable=False)
    chunk_index = db.Column(db.Integer, nullable=False)
    chunk_size = db.Column(db.Integer, nullable=False)
    stored_path = db.Column(db.String(255), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    upload_task = db.relationship('FileUploadTask', backref='chunks')